<?php

namespace app\admin\model\admin;

use think\Model;
use think\Session;
use utils\Random;
/**
 * 超管后台用户模型
 * Class User
 * @package app\admin\model\admin
 */
class User extends Model{
    protected $name='yonghui_adminuser';
    /**
     * 超管后台用户登录
     */
    public function login($data){
        $user=self::where(['name' => $data['user_name']])->find();
        if(!$user){
            $this->error = '登录失败, 用户名不存在';
            return false;
        }else{
            if($user['status']==2){
                $this->error = '登录失败, 该账号已被禁用';
                return false;
            }
            $pass = md5($data['password']);
            if($pass==$user['password']){
                //保存登录状态
                Session::set('yoshop_adminuser', [
                    'user' => [
                        'type'=>$user['type'],
                        'status'=>$user['status'],
                        'company_id'=>$user['companyId'],
                        'admin_user_id' => $user['id'],
                        'user_name' => $user['name'],
                    ],
                    'is_login' => true,
                ]);
                return true;
            }else{
                $this->error = '登录失败, 用户名或密码错误';
                return false;
            }
        }
    }

    /**
     * 超管用户信息
     * @param $admin_user_id
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function detail($admin_user_id){
        return self::get($admin_user_id);
    }

    /**
     * 关联用户角色表表
     * @return \think\model\relation\BelongsToMany
     */
    public function role(){
        return $this->belongsToMany('Role', 'UserRole');
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete(){
        if ($this['is_super']) {
            $this->error = '超级管理员不允许删除';
            return false;
        }
        // 删除对应的角色关系
        UserRole::deleteAll(['store_user_id' => $this['store_user_id']]);
        return $this->save(['is_delete' => 1]);
    }
    /**
     * 更新当前管理员信息
     */
    public function renew($data){
        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        // 更新管理员信息
        if ($this->allowField(true)->save([
                'name'=> $data['name'],
                'password' => md5($data['password']),
            ]) === false) {
            return false;
        }
        // 更新session
       /* Session::set('yoshop_adminuser.user', [
            'admin_user_id' => $this['admin_user_id'],
            'user_name' => $data['user_name'],
        ]);*/
        Session::set('yoshop_adminuser', [
            'user' => [
                'type'=>$this['type'],
                'status'=>$this['status'],
                'company_id'=>$this['companyId'],
                'admin_user_id' => $this['id'],
                'user_name' => $this['name'],
            ],
            'is_login' => true,
        ]);
        return true;
    }
    /**
     * 验证用户名是否重复
     * @param $userName
     * @return bool
     */
    public static function checkExist($userName){
        return !!static::useGlobalScope(false)
            ->where('user_name', '=', $userName)
            ->where('is_delete', '=', 0)
            ->value('admin_user_id');
    }

    /**
     * 获取用户列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList(){
        return $this->where('is_delete', '=', '0')
            ->order(['createTime' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 新增记录
     * @param $data
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public function add($data){
        if (self::checkExist($data['user_name'])){
            $this->error = '用户名已存在';
            return false;
        }
        if ($data['password'] !== $data['password_confirm']){
            $this->error = '确认密码不正确';
            return false;
        }
        if (empty($data['role_id'])) {
            $this->error = '请选择所属角色';
            return false;
        }
        $this->startTrans();
        try {
            // 新增管理员记录
            $data['salt'] = Random::alnum();
            $data['password'] = md5(md5($data['password']) . $data['salt'].config('salt'));
            $data['is_super'] = 0;
            $this->allowField(true)->save($data);
            // 新增角色关系记录
            (new UserRole)->add($this['admin_user_id'], $data['role_id']);
            $this->commit();
            return true;
        } catch (\Exception $e){
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }
}